package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.example.exception.AppException;
import org.example.exception.AppExceptionCodeMsg;
import org.example.pojo.CheckRequest;
import org.example.pojo.Cost;
import org.example.pojo.Prescription;
import org.example.query.CostQuery;
import org.example.service.ICheckRequestService;
import org.example.service.ICostService;
import org.example.service.IPrescriptionService;
import org.example.vo.ResultBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/cost")
@RestController
public class CostController extends  BaseController<Cost, CostQuery> {
    private static final Logger log = LoggerFactory.getLogger(CostController.class);
    @Autowired
    ICostService costService;
    @Autowired
    ICheckRequestService checkRequestService;
    @Autowired
    IPrescriptionService prescriptionService;
    @Transactional
    @PostMapping("/pay")
    public ResultBean pay(@RequestBody CostQuery costQuery){

//        System.out.println(costQuery.toString());
//        if (costQuery==null||
//                StringUtils.isNotEmpty(costQuery.getPayMethod()) ||
//                costQuery.getSettleCategoryId()==null)   {
//            System.out.println("-----------");
//            throw new AppException(AppExceptionCodeMsg.PARAMS_EMPTY);
//        }
        //先更新收费表中的支付状态
        //state
        boolean update = costService.update(costQuery.getUpdateWrapper());

        if(!update){
            ResultBean.ERROR("支付失败");
        }
        //在费用的时候不光添加检查的费用还要添加药品的费用
        costQuery.getIds().forEach(costId->{
            Cost cost = costService.getOne(new QueryWrapper<Cost>().eq("id", costId));
            String costtype = cost.getCosttype();
            if ("检查".equals(costtype)){
                //再去更改挂号表中的缴费状态
                //refId就是挂号表中的id
                //在检查表中去查找refId然后更新check_state状态
                UpdateWrapper<CheckRequest> updateWrapper = new UpdateWrapper<>();
                log.info("检查单中id值为："+cost.getRefId());
                //这里报错，是因为在检查单中并没有查询出来的id值，所以进行了报错
                updateWrapper.set("check_state","已缴费")
                        .eq("id",cost.getRefId());
                boolean up = checkRequestService.update(updateWrapper);
                if(!up){
                    throw new AppException(300003,"更新检查申请状态失败");
                }
            } else if("药品".equals(costtype)){
                //当进行费用表更新完之后，就去更新处方表的中缴费状态
                UpdateWrapper<Prescription> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("drug_state","已缴费")
                        .eq("id",cost.getRefId());
                boolean up1=prescriptionService.update(updateWrapper);
                if(!up1){
                    throw new AppException(300004,"更新药品缴费状态失败");
                }
            }
        });

        return ResultBean.SUCCESS();
    }
    @PostMapping("/conditions")
    public ResultBean conditions(@RequestBody CostQuery costQuery){
        QueryWrapper<Cost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("register_id",costQuery.getRegisterId());
        List<Cost> costs = costService.list(queryWrapper);
        return ResultBean.SUCCESS(costs);
    }

    @Override
    @DeleteMapping("/del/{id}")
    public ResultBean delete(@PathVariable("id") Integer id) throws Exception {
        if(id == null){
            throw new AppException(AppExceptionCodeMsg.PARAMS_EMPTY);
        }
        Cost cost = costService.getOne(new QueryWrapper<Cost>().eq("id",id));
        String costtype = cost.getCosttype();
        //数据问题
        if("检查".equals(costtype)){
            boolean del = checkRequestService.removeById(cost.getRefId());

            if(!del){
                throw new AppException(70002,"删除检查申请失败");
            }
        }else if("药品".equals(costtype)){

            boolean del = prescriptionService.removeById(cost.getRefId());
            if(!del){
                throw new AppException(500004,"删除处方失败");
            }
        }

        boolean delete = costService.removeById(id);

        if(!delete){
            throw new AppException(70001,"删除失败");
        }

        return ResultBean.SUCCESS();
    }

    @Transactional
    @PostMapping("/refund")
    public ResultBean refund(@RequestBody CostQuery costQuery){

        if(costQuery==null||costQuery.getState()==null){
            throw new AppException(AppExceptionCodeMsg.PARAMS_EMPTY);
        }

        boolean update = costService.update(costQuery.getRefundWrapper());

        if(!update){
            throw new AppException(60001,"退费失败");
        }

        Cost cost = costService.getOne(new QueryWrapper<Cost>().eq("id",costQuery.getId()));
        String costtype = cost.getCosttype();
        if("检查".equals(costtype)){
            UpdateWrapper<CheckRequest> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("check_state","已退费")
                    .eq("id",cost.getRefId());
            boolean up = checkRequestService.update(updateWrapper);

            if(!up){
                throw new AppException(60002,"更新检查申请状态失败");
            }
        }else if("药品".equals(costtype)){
            UpdateWrapper<Prescription> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("drug_state","已退费")
                    .eq("id",cost.getRefId());
            boolean up = prescriptionService.update(updateWrapper);
            if(!up){
                throw new AppException(400004,"更新药品缴费状态失败");
            }
        }

        return ResultBean.SUCCESS();


    }

}
